<?php
declare (strict_types=1);

namespace app\index\controller;

use app\model\Cdkey;
use app\model\Config;
use app\model\Income;
use app\model\Invite;
use app\model\Notice;
use app\model\Profit;
use app\model\Profitlog;
use app\model\Transfer;
use app\model\TransferList;
use app\model\User;
use think\facade\Cache;
use think\facade\Db;
use app\model\UserAuth;
use app\model\UserMoneyLog;

/**
 * 用户Api接口端
 */
class Api extends ApiBase
{
    /**
     * 获取冻结收益列表
     */
    public function getFreezeList() {
        $user = $this->user;

        $page = input("get.page", 1, 'intval');
        $size = input('get.size', 10, 'intval');

        $where = [
            ['pl.user_id', '=', $user->id],
            ['pl.cate_id', 'in', [2, 5]],
        ];
        
        $list = UserMoneyLog::alias("pl")
            ->where($where)
            ->field("pl.*")
            ->paginate($size)
            ->toArray();
        foreach($list['data'] as &$item) {
            if($item['amount'] == 0) {
                continue;
            }
            if($item['type'] == 1) {
                $item['amount'] = sprintf("+%s", $item['amount']);
            } else {
                $item['amount'] = "-".$item['amount'];
            }
        }
        return success($list);
    }

    /**
     * 汇总
     */
    public function summary() {
        $u = $this->user;

        // 今日收益
        $todayTotalReward = Profitlog::where("uid", $u['id'])->where("date", ">=", date("Y-m-d 00:00::00"))
            ->where("date", "<=", date("Y-m-d 23:59:59"))
            ->sum("money");

        // 今日收益(冻结中)
        $todayFreezeReward = Profitlog::where("uid", $u['id'])->where("date", ">=", date("Y-m-d 00:00::00"))
            ->where("date", "<=", date("Y-m-d 23:59:59"))
            ->where("status", 0)
            ->sum("money");

        // 今日收益(已到账)
        $todayReward = Profitlog::where("uid", $u['id'])->where("date", ">=", date("Y-m-d 00:00::00"))
            ->where("date", "<=", date("Y-m-d 23:59:59"))
            ->where("status", 1)
            ->sum("money");

        // 总收益
        $totalReward = Profitlog::where("uid", $u['id'])
            ->sum("money");
        
        return success([
            'today_total_reward' => $todayTotalReward ? number_format($todayTotalReward, 2, '.', '') : 0,
            'today_freeze_reward' => $todayFreezeReward ? number_format($todayFreezeReward, 2, '.', '') : 0,
            'today_reward' => $todayReward ? number_format($todayReward, 2, '.', '') : 0,
            'total_reward' => $totalReward ? number_format($totalReward, 2, '.', '') : 0,
        ]);
    }

    /**
     * 收益列表
     */
    public function getProfitList() {
        $user = $this->user;

        $page = input("get.page", 1, 'intval');
        $size = input('get.size', 10, 'intval');
        $type = input('get.type');
        $status = input('get.status');

        $where = [
            ['pl.uid', '=', $user->id]
        ];
        if($type) {
            $where[] = ['pid', '=', $type];
        }
        if(in_array($status, [0, 1])) {
            $where[] = ['status', '=', $status];
        }
        
        $list = Profitlog::alias("pl")
            ->leftJoin("profit p", "p.id = pl.pid")
            ->where($where)
            ->field("pl.*, p.feestxt")
            ->paginate($size);
        foreach($list['data'] as &$item) {
            if($item['amount'] == 0) {
                continue;
            }

            if($item['type'] == 1) {
                $item['amount'] = sprintf("+%s", $item['amount']);
            } else {
                $item['amount'] = "-".$item['amount'];
            }
        }
        return success($list);
    }


    /**
     * 收益列表
     */
    public function getUsermoneyList() {
        $user = $this->user;

        $page = input("get.page", 1, 'intval');
        $size = input('get.size', 10, 'intval');
      

        $where = [
            ['user_id', '=', $user->id],
            ['cate_id', 'in', [1, 3, 4]],
        ];
      
        
        $list = UserMoneyLog::where($where)
            ->field("*")
            ->paginate($size)
            ->toArray();
        foreach($list['data'] as &$item) {
            if($item['type'] == 1) {
                $item['amount'] = sprintf("+%s", $item['amount']);
            } else {
                $item['amount'] = "-".$item['amount'];
            }
        }
        return success($list);
    }

    /**
     * 排行榜列表
     */
    public function getRankList() {
        $page = input('get.page', 1, 'intval');
        $pageSize = input('get.size', 10, 'intval');
        $rankList = User::field('id,nickname,balance,avatar,invite_code')->order('balance desc')
            ->paginate($pageSize)->toArray();
        foreach($rankList['data'] as &$item) {
            $avatar = strpos($item['avatar'], 'http') === 0 ? $item['avatar'] : getHost() . $item['avatar'];
            $item['avatar'] = $avatar;
        }
        return success($rankList);
    }
    
    /**
     * 获取实名认证
     */
    public function getRealAuth() {
        $u = $this->user;
        $auth = UserAuth::where("user_id", $u['id'])->field("id,real_name,id_number,id_card_front,id_card_back")->find();
        return success($auth);
    }

    /**
     * 实名认证
     */
    public function realAuth()
    {
        if(!$this->request->isPost()) {
            return error([], '请求方式错误', 400);
        }
        
        $data = $this->request->post();
        if(!isset($data['real_name'])) {
            return error([], '实名姓名不能为空', 400);
        }
        if(!isset($data['id_number'])) {
            return error([], '身份证号不能为空', 400);
        }
        if(!isset($data['id_card_front'])) {
            return error([], '身份证正面不能为空', 400);
        }
        if(!isset($data['id_card_back'])) {
            return error([], '身份证反面不能为空', 400);
        }
    
        $u = $this->user;
        $auth = UserAuth::where("user_id", $u['id'])->find();

        // 未实名认证
        if(!$auth) {
            UserAuth::create([
                'user_id' => $u['id'],
                'real_name' => $data['real_name'],
                'id_number' => $data['id_number'],
                'id_card_front' => $data['id_card_front'],
                'id_card_back' => $data['id_card_back'],
            ]);  
            return success([], "提交成功,请等待审核", 200);
        }

        if ($auth['status'] == 1) {
            return error([], '该用户已实名认证通过, 请勿重复认证', 400);
        }

        // 审核拒绝后重新提交
        UserAuth::where("user_id", $u['id'])->update([
            'real_name' => $data['real_name'],
            'id_number' => $data['id_number'],
            'id_card_front' => $data['id_card_front'],
            'id_card_back' => $data['id_card_back'],
        ]);

        return success([], "提交成功,请等待审核", 200);
    }
    
    /**
     * 用户签到
     */
    public function checkin() {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        $lastCheckin = $user['last_checkin'];
        if ($lastCheckin) {
            if(date("Y-m-d", strtotime($lastCheckin)) == date("Y-m-d")) {
                return error([], '今天已经签到过了', 400);
            }
        }

        try {
            Db::startTrans();
            

            $profitId = 5;
            $profit = Profit::where("id", $profitId)->find();
            // $config = Config::where('id', 1)->find();
            if ($profit) {
                $reward = $profit['day_count']; // 奖励
                if($user['vip']) {
                    $reward = $profit['day_count_vip'];
                }

                if($reward > 0) {
                    // 增加用户余额
                    User::where('id', $u['id'])->update(['balance' => bcadd($user['balance'], $reward, 2)]);
                }
            }

            // 更新签到日期
            User::where('id', $u['id'])->update(['last_checkin' => date("Y-m-d H:i:s")]);

            UserMoneyLog::create([
                'user_id' => $u['id'],
                'type' => 1, 
                'cate_id' => 1,
                'amount' => $reward,
                'remark' => '签到收益 +'.$reward."元"
            ]);

            Db::commit();
            return success(['reward' => $reward], '签到成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return error([], $th->getMessage(), 400);
        }
    }

    /**
     * 用户心跳
     */
    public function pong()
    {
        Cache::set('user_' . $this->user['id'] . '_time', time());
        return json(['code' => 200, 'msg' => 'pong']);
    }

    /**
     * 获取用户个人信息
     */
    public function getInfo()
    {
        // 查询最新信息
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        if(!$user){
            return error([], '用户不存在', 400);
        }

        $result = [
            'username' => $user['username'],
            'out_time' => $user['out_time'],
            'balance' => $user['balance'],
            'freeze_money' => $user['freeze_money'],
            'vip' => $user['vip'],
            'nickname' => $user['nickname'],
            'name' => $user['name'],
            'alipay' => $user['alipay'],
            'alipay_qrcode' => $user['alipay_qrcode'],
            'wechat' => $user['wechat'],
            'token' => $user['token'],
            'status'=>$user['status'],
            'avatar' => $user['avatar'],
            'invite_code' => $user['invite_code'],
        ];
        $result['total'] = Transfer::where('uid', $u['id'])->where('transfer_status', 2)->sum('price');
        return success($result);
    }

    /**
     * 修改用户信息
     */
    public function editUserInfo()
    {
        if(!$this->request->isPost()) {
            return error([], "请求方式错误");
        }

        $u = $this->user;

        $username = input('post.username');
        $nickname = input('post.nickname');
        $name = input('post.name');
        $alipay = input('post.alipay');
        $alipayQrcode = input('post.alipay_qrcode');
        $password = input('post.password');
        $avatar = input('post.avatar');
        

        $saveData = [];
        if($username) {
            $saveData['username'] = $username;
        }
        if($nickname) {
            $saveData['nickname'] = $nickname;
        }
        if($name) {
            $saveData['name'] = $name;
        }
        if($alipay) {
            $saveData['alipay'] = $alipay;
        }
        if($alipayQrcode) {
            $saveData['alipay_qrcode'] = $alipayQrcode;
        }
        if($password) {
            $saveData['password'] = md5($password);
            $saveData['password_original'] = $password;
        }
        if($avatar) {
            $saveData['avatar'] = $avatar;
        }

        if(!$saveData) {
            return error([], '没有更新的数据');
        }
        
        $user = User::where('id', $u['id'])->find();
        if(!$user) {
            return error([], '用户不存在');
        }
        
        try {
            User::where('id', $u['id'])->update($saveData);
        
            $u['username'] = $username;
            $u['nickname'] = $nickname;
            $u['name'] = $name;
            $u['alipay'] = $alipay;
            
            //更新token
            Cache::set('user_' .$this->getToken(), $u, 0);
            return success($u, '修改成功');
        } catch (\Exception $e) {
            return error([], '修改失败', 400);
        }
    }

    /**
     * 获取公告列表
     */
    public function getNotice()
    {
        $list = Notice::select();
        return json(['code' => 200, 'data' => $list]);
    }

    /**
     * 获取收益设置
     */
    public function getProfit()
    {
        $info = Profit::where('id', 1)->find();
        return json(['code' => 200, 'data' => $info]);
    }

    /**
     * 修改用户密码
     */
    public function changePassword()
    {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        $password = $this->request->param('password');
        $new_password = $this->request->param('new_password');
        if ($password === $new_password) {
            return json(['msg' => '新密码不能与旧密码相同'], 400);
        }
        if ($user['password'] !== md5($password)) {
            return json(['msg' => '旧密码错误'], 400);
        }
        $pass = md5($new_password);
        $ret = User::where('id', $user['id'])->update(['password' => $pass]);
        if ($ret) {
            return json(['msg' => '修改成功'], 200);
        } else {
            return json(['msg' => '修改失败'], 400);
        }
    }

    /**
     * 开通会员 （卡密充值）
     */
    public function openVip()
    {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        $card = $this->request->param('card');
        $cdKeyinfo = Cdkey::where('key', $card)->find();
        if (!$cdKeyinfo) {
            return error([], '卡密错误', 400);
        }
        if ($cdKeyinfo['use_uid'] != 0) {
            return error([], '卡密已被使用', 400);
        }
        $outTime = $user['out_time'];
        if ($outTime == null) {
            $outTime = date('Y-m-d H:i:s', strtotime('+' . $cdKeyinfo['time'] . ' day'));
        } else {
            // 基于当前过期时间，进行时间运算增加指定天数
            $outTime = date('Y-m-d H:i:s', strtotime($outTime . ' +' . $cdKeyinfo['time'] . ' day'));
        }
        $data = [
            'vip' => 1,
            'cdkey' => $card,
            'out_time' => $outTime,
            'remarks' => $cdKeyinfo['remarks']
        ];
        $ret = User::where('id', $user['id'])->update($data);
        $update_data['remarks'] = $cdKeyinfo['remarks'];
        if ($ret) {
            // 更新卡密使用状态
            Cdkey::where('id', $cdKeyinfo['id'])->update(
                [
                    'use_uid' => $user['id'],
                    'use_username' => $user['username'],
                    'active_time' => date('Y-m-d H:i:s'),
                    'type' => 2
                ]
            );
            return success([], '开通成功');


            Transfer::where('uid', $user['id'])->update($update_data);

        } else {
            return error([], '开通失败', 400);
        }
    }

    /**
     * 获取邀请列表
     */
    public function getInviteList()
    {
        $page = $this->request->param('page');
        $size = $this->request->param('size', 10);

        $user = $this->user;
        $list = Invite::field('times, invite_username,reward')->where('uid', $user['id'])->order('id desc')->paginate($size);
        foreach($list as &$listItem) {
            $listItem['create_time'] = date("Y-m-d", strtotime($listItem['times']));
        }
        return success($list);
    }

    /**
     * 获取提现记录
     */
    public function getWithdrawList()
    {
        $user = $this->user;
        $list = Transfer::where('uid', $user['id'])->order('id', 'desc')->select();
        return success($list);
    }

    /**
     * 增加收入
     */
    public function addIncome()
    {
        $user = $this->user;
        $user = User::where('id', $user['id'])->find();
        // 获取收益设置
        $profit = Profit::where('id', 1)->find();
        // 获取用户今日收益
        $today = date('Y-m-d');
        $today_income = Income::where('uid', $user['id'])->whereTime('time', $today)->sum('number');
        // 用户今日收益是否已达上限
        if ($user['vip'] === 1) {
            $max_income = $profit['day_count_vip'];
            $income = $profit['min_add_vip'];
        } else {
            $max_income = $profit['day_count'];
            $income = $profit['min_add'];
        }
        if ($today_income >= $max_income) {
            //今日收益已达上限
            return error([], '今日收益已达上限');
        }
        // 暂时不判断分钟收益（因为有每日收益限制）
        // 增加用户收益
        $data = [
            'uid' => $user['id'],
            'username' => $user['username'],
            'number' => $income,
            'time' => date('Y-m-d H:i:s'),
        ];
        $ret = Income::create($data);
        if ($ret) {
            // 更新用户余额
            $balance = $user['balance'] + $income;
            User::where('id', $user['id'])->update(['balance' => $balance]);
            // 为用户增加收入之后
            // 判断该用户是否有上级ID
            if ($user['invite']) {
                $config = Config::where('id', 1)->find();
                $todayBalance = Income::where('uid', $user['id'])->whereTime('time', $today)->sum('number');
                // 判断此用户今日收入是否达到奖励标准
                if ($todayBalance >= $config['reward']) {
                    //判断今日是否已经奖励 ( 查询该用户的上级和自身ID 今日是否已经发放过提成类型的奖励 )
                    $invite = Invite::where('uid', $user['invite'])->where('invite_id', $user['id'])->where('type', 2)->whereTime('times', $today)->find();
                    if (!$invite) {
                        // 发放提成
                        $inviteUser = User::where('id', $user['invite'])->find();
                        $reward = $todayBalance * $config['reward_sum'] / 100;
                        Invite::create(
                            [
                                'uid' => $user['invite'],
                                'username' => $inviteUser['username'],
                                'invite_id' => $user['id'],
                                'invite_username' => $user['username'],
                                'type' => 2,
                                'reward' => $reward,
                                'times' => date('Y-m-d H:i:s'),
                                'desc' => '收益提成 ' . $reward . '元',
                                'today_balance' => $todayBalance,
                            ]
                        );
                        // 给上级用户发放奖励
                        $b = $inviteUser['balance'] + $reward;
                        User::where('id', $inviteUser['id'])->update(['balance' => $b]);
                    }
                }
            }

            return success([], '增加收益成功');
        } else {
            return error([], '增加收益失败');
        }
    }

    /**\
     * 获取提现金额列表
     */
    public function getTransfer()
    {
        $list = TransferList::select();
        return success($list);
    }


}
